package com.example.basesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.basesystem.entity.SysMenu;
import com.example.basesystem.mapper.SysMenuMapper;
import com.example.basesystem.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单服务实现类
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<String> getPermissionsByUserId(Long userId) {
        return sysMenuMapper.selectPermsByUserId(userId);
    }

    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        return sysMenuMapper.selectMenusByUserId(userId);
    }

    @Override
    public List<SysMenu> getMenusByRoleId(Long roleId) {
        return sysMenuMapper.selectMenusByRoleId(roleId);
    }

    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        // 获取所有根菜单
        List<SysMenu> rootMenus = menus.stream()
                .filter(menu -> menu.getParentId() == 0)
                .collect(Collectors.toList());

        // 构建子菜单
        for (SysMenu rootMenu : rootMenus) {
            buildChildrenMenu(rootMenu, menus);
        }

        return rootMenus;
    }

    /**
     * 递归构建子菜单
     */
    private void buildChildrenMenu(SysMenu parentMenu, List<SysMenu> menus) {
        List<SysMenu> childrenMenus = menus.stream()
                .filter(menu -> parentMenu.getId().equals(menu.getParentId()))
                .collect(Collectors.toList());

        if (!childrenMenus.isEmpty()) {
            parentMenu.setChildren(childrenMenus);
            for (SysMenu childMenu : childrenMenus) {
                buildChildrenMenu(childMenu, menus);
            }
        }
    }
}